
require "rubygems"

class SkyDrive
  require "mechanize"
  INIT_URL = "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1304302574&rver=6.1.6206.0&wp=MBI&wreply=http:%2F%2Fskydrive.live.com%2Fhome.aspx&lc=1041&id=250206&cbcxt=sky" # sign in URL
  UA        = "Fighter Zero/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"
  FileTypes = %w[f f f d f f f f f f f d d d f d d f]
  def initialize(liveid, pass)
    @m = Mechanize.new
    @m.user_agent = UA
    @m.get(INIT_URL)
    if (/\<input type=\"hidden\" name=\"PPFT\" id=\"i0327\" value=\"([^\"]+)\"/ =~ @m.page.body) then
      ppft = $1
    end
    if (/srf_uPost=\'([^\']+)'/ =~ @m.page.body) then
      srf_uPost = $1
    end
    post_uri = URI.parse(srf_uPost);
    c = Mechanize::Cookie.new("CkTst", "G" + Time.new.gmtime.to_s)
    c.domain = "login.live.com"
    c.path = "/"
    @m.cookie_jar.add(post_uri, c)
    c = Mechanize::Cookie.new("wildPerf", "throughput=7&latency=421&FR=L&ST=" + Time.new.gmtime.to_s)
    c.domain = ".live.com"
    c.path = "/"
    @m.cookie_jar.add(post_uri, c)


    params = {}
    params["idsbho"] = "1"
    params["PwdPad"] = "IfYouAreReadingThisYouHaveTooMu"
    params["LoginOptions"] = "3"
    params["CS"] = ""
    params["FedState"] = ""
    params["PPSX"] = "Pas"
    params["type"] = "11"
    params["login"] = liveid
    params["passwd"] = pass
    params["NewUser"] = "1"
    params["PPFT"] = ppft
    params["i1"] = "0"
    params["i2"] = "0"
    @m.redirect_ok = true
    @m.follow_meta_refresh = true
    @m.post(srf_uPost, params);
    @m.page.form_with(:name=>"fmHF") do | form |
      form.click_button
    end
    @cwd = "/"
  end
  def ls
    print @m.page.body
    f_names = []
    @m.page.search("//a[@class='tvLink']").each do |l|
      
      fname =  l.to_s.gsub(/\<[^>]*>/, "")
      f_names.push(fname);
    end
    f_types = []
    @m.page.search("//img[@style='width:48px;height:864px;']") .each do |ft|
      if(/smallIconsSprite_0_\-(\d+)_48_48/ =~ ft.to_s)
        ti = $1.to_i / 48
        f_types.push(FileTypes[ti])
      end
    end
    i = 0
    f_names.each do | f_name |
      puts f_types[i] + " " + f_name
      i += 1
    end
  end
end


if(__FILE__ == "skydrive.rb") then
  sd = SkyDrive.new(ENV["LIVEID"], ENV["LIVEPASS"])
  sd.ls

end
